package sword.chapter8Tree;

import java.util.Stack;

/**
 * 二叉搜索树的下一个结点
 *
 * 中序遍历
 *
 * @author K
 * @date 2021-12-12 17:22
 */
public class S53InorderSuccessor {

    /**
     * O(n)
     */
    public static TreeNode s53(TreeNode root, TreeNode p) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if (cur == p) {
                return cur.right;
            }
            cur = cur.right;
        }
        return null;
    }

    /**
     * O(h)
     */
    public static TreeNode s53A(TreeNode root, TreeNode p) {
        TreeNode cur = root;
        while (cur != null) {
            if (cur == p) {
                return cur.right;
            }
            if (cur.val > p.val) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        TreeNode node2 = new TreeNode(2);
        TreeNode node5 = new TreeNode(5);
        TreeNode node1 = new TreeNode(1);
        TreeNode node3 = new TreeNode(3);
        TreeNode node6 = new TreeNode(6);
        root.left = node2;
        root.right = node5;
        node2.left = node1;
        node2.right = node3;
        node5.right = node6;

        TreeNode result = s53(root, root);
        TreeNode result2 = s53A(root, node5);
        System.out.println();
    }
}
